#include "../lib_include/Timestamp.h"

#include <sys/time.h>
#include <stdio.h>
#include <inttypes.h>

#ifndef __STDC_FORMAT_MACROS // 跨平台优化，本类中针对PRId64
#define __STDC_FORMAT_MACROS
#endif

using namespace netlib;

// static_assert:静态断言，编译时判断，assert运行时判断
static_assert(sizeof(Timestamp) == sizeof(int64_t),
              "Timestamp should be same size as int64_t");


// int64_t是64位的长整形，64位系统中打印格式printf("%ld",value),32位系统中printf("%lld",value)
// 声明跨平台宏后，无论64或者32位系统，都使用printf("%d"PRId64,value)即可
string Timestamp::toString() const // 将秒数转化成string返回
{
    char buf[32] = {0};
    int64_t seconds = microSecondsSinceEpoch_ / kMicroSecondsPerSecond;
    int64_t microseconds = microSecondsSinceEpoch_ % kMicroSecondsPerSecond;
    snprintf(buf, sizeof(buf), "%" PRId64 ".%06" PRId64 "", seconds, microseconds);
    return buf;
}

// 将时间转化成年月日时分秒形式，转换成string返回 
string Timestamp::toFormattedString(bool showMicroseconds) const
{
    char buf[64] = {0};
    time_t seconds = static_cast<time_t>(microSecondsSinceEpoch_ / kMicroSecondsPerSecond);
    struct tm tm_time;
    gmtime_r(&seconds, &tm_time);

    if (showMicroseconds) // tm_time.tm_hour+8 因为北京处于东八区，小时数需要加8
    {
        int microseconds = static_cast<int>(microSecondsSinceEpoch_ % kMicroSecondsPerSecond);
        snprintf(buf, sizeof(buf), "%4d-%02d-%02d %02d:%02d:%02d.%06d ",
                tm_time.tm_year + 1900, tm_time.tm_mon + 1, tm_time.tm_mday,
                tm_time.tm_hour+8, tm_time.tm_min, tm_time.tm_sec,
                microseconds);
    }
    else
    {
        snprintf(buf, sizeof(buf), "%4d-%02d-%02d %02d:%02d:%02d ",
                tm_time.tm_year + 1900, tm_time.tm_mon + 1, tm_time.tm_mday,
                tm_time.tm_hour+8, tm_time.tm_min, tm_time.tm_sec);
    }
    return buf;
}

Timestamp Timestamp::now()
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    int64_t seconds = tv.tv_sec;
    return Timestamp(seconds * kMicroSecondsPerSecond + tv.tv_usec);
}
